<?php

namespace app\agentapi\controller\user;
use app\agentapi\controller\Controller;
use think\Db;
use think\Image;
use OSS\OssClient;
use app\admin\model\BaseSetting as SettingModel;
use app\admin\model\article\UploadFile;
use think\Cache;
use app\common\service\qrcode\Gifts as GiftsModel;
use app\agentapi\model\Sms;
use think\Log;
/**
 * 用户
 */
class User extends Controller{
    private $config;
    public function _initialize(){
        //parent::_initialize();
        // 存储配置信息
        $this->config = SettingModel::getItem('storage');
    }
    /**
     * 小程序首页
     */
    public function index(){
        $info=Db::name('love_notice')->where(['status'=>1])->select()->toArray();
        $newa=[];
        foreach ($info as $k=>$v){
            //1:logo 2:广告位 3：通知 4：销售榜
            $image=Db::name('upload_file')->where(['file_id'=>$v['imageId']])->field('file_id,file_url,file_name')->find();
            if($image){
                $v['imageurl']=$image['file_url'].'/'.$image['file_name'];
            }else{
                $v['imageurl']=[];
            }
            if($v['type']==1){
                $newa['logo'][]=$v;
            }if($v['type']==2){
                $newa['guanggao'][]=$v;
            }
            if($v['type']==3){
                $newa['tongzhi'][]=$v;
            }
            if($v['type']==4){
                $newa['xiaoshou'][]=$v;
            }
        }
        return json(['msg'=>'获取成功','code'=>'success','data'=>$newa]);
    }
    /**
     * 客户录入
     */
    public function addCustomer(){
        /*1.销售管理员，置业顾问，楼管人员可以录入客户
          2.客户类型分为买  卖  出租  求租
        */
        $data=[];
        $userInfo=Db::name('love_admin_user')->where(['id'=>$this->userId])->field('id,type')->find();
        //公共字段
        if($userInfo['type']==6){
            //楼管人员  1.自录 2：楼管录入
            $iszilu=2;
        }else{
            $iszilu=1;
        }
        $data['datatype']=input('post.datatype');//客户类型
        $data['name']=input('post.name');//名称
        $data['phone']=input('post.phone');//电话
        $data['gender']=input('post.gender');//性别
        $data['status']=1;//1:跟进中 2：已付订 3.已签约 4.预失效 5.失效
        $data['inputuserid']=$this->userId;//录入人id
        $data['create_time']=time();//创建时间
        $data['inputusertype']=$userInfo['type'];//录入人类型 1：主管理员 2：城市管理员 3：区域管理员 4:销售管理员  5：置业顾问 6：楼管人员
        $data['iszilu']=$iszilu;
        //买  求租
        $data['flagid']=input('post.flagid');//意向类型 意向类型id（新房，二手，文旅）
        $data['cityid']=input('post.cityid');//意向城市
        $data['areaid']=input('post.areaid');//意向区域

        $data['loupanid']=input('post.loupanid');//意向楼盘
        $data['danjia']=input('post.danjia');//意向月租金/意向单价
        $data['paytype']=input('post.paytype');//买：分期 全款  租：押三付一 /押一付一 /月结/无
        $data['payments']=input('post.payments');//首付预算金额
        $data['measure']=input('post.measure');//意向楼盘面积
        $data['huxing']=input('post.huxing');//意向户型
        $data['detail']=input('post.detail');//补充信息

        if($iszilu==1){
            //根据录入人身份判断 客户意向楼盘是否是自己负责
            if($data['datatype']==2||$data['datatype']==3){
                $data['floweuserid']=$this->userId;//跟进人id
                $data['fenpei_time']=time();
            }
            if($data['datatype']==1||$data['datatype']==4){
                $lid=Db::name('love_admin_user')->where(['id'=>$this->userId])->value('loupanids');
                if($userInfo['type']==4){
                    $lids=explode(',',$lid);
                    if(in_array($data['loupanid'],$lids)){
                        $data['floweuserid']=$this->userId;//跟进人id
                        $data['fenpei_time']=time();
                    }
                }
                if($userInfo['type']==5){
                    if($data['loupanid']==$lid){
                        $data['floweuserid']=$this->userId;//跟进人id
                        $data['fenpei_time']=time();
                    }
                }
            }
        }
        if(empty($data['flagid'])){
            return json(['msg'=>'请选择意向类型','code'=>'error','data'=>[]]);
        }
        if(empty($data['cityid'])){
            return json(['msg'=>'请选择意向城市','code'=>'error','data'=>[]]);
        }
        if(empty( $data['areaid'])){
            return json(['msg'=>'请选择意向区域','code'=>'error','data'=>[]]);
        }
        if(empty($data['loupanid'])){
            return json(['msg'=>'请选择意向楼盘','code'=>'error','data'=>[]]);
        }
        //同一客户在同一类型中只能录入一次
        $customer=Db::name('love_customer')->where(['datatype'=>$data['datatype'],'phone'=>$data['phone'],'status'=>['in','1,2,4']])->field('id')->find();
        if($customer){
            return json(['msg'=>'当前类型客户已录入过','code'=>'error','data'=>[]]);
        }
        $insert=Db::name('love_customer')->insertGetId($data);
        if($insert){
            //写入操作日志记录
            $insertData['userid']=$this->userId;
            $insertData['datatype']=1;
            $insertData['customerid']=$insert;
            $insertData['fromType']=2;
            $insertData['remark']='报备客户';
            $insertData['create_time']=time();
            Db::name('love_log')->insert($insertData);
            return json(['msg'=>'报备成功','code'=>'success','data'=>[]]);
        }
        return json(['msg'=>'报备失败','code'=>'error','data'=>[]]);
    }
    /**
     * 编辑客户信息
     */
    public function editCustomer(){
        //查看  info  编辑  edit
        $flag=input('post.flag');
        $customerId=input('post.customerId');//客户id
        if(empty($customerId)){
            return json(['msg'=>'客户id不能为空','code'=>'error','data'=>[]]);
        }
        $customerInfo=Db::name('love_customer')->where(['id'=>$customerId])->find();
        if($flag=='info'){
            //查看，获取客户当前基本信息 ,凭证信息，跟进信息
            if(empty($customerInfo)){
                return json(['msg'=>'未获取到客户信息','code'=>'error','data'=>[]]);
            }
            //获取凭证信息，只获取当前跟进人填写的凭证信息，跟进信息
            //意向楼盘
            $build=Db::name('love_building')->where(['id'=>$customerInfo['loupanid']])->field('id,name')->find();
            if($build){
                $customerInfo['buildName']=$build['name'];
            }else{
                $customerInfo['buildName']='暂无';
            }
            //城市，区域
            $areaInfo=Db::name('love_area')->where(['id'=>$customerInfo['cityid']])->field('id,name')->find();
            if($areaInfo){
                $customerInfo['cityname']=$areaInfo['name'];
            }else{
                $customerInfo['cityname']='暂无';
            }
            $cityInfo=Db::name('love_area')->where(['id'=>$customerInfo['areaid']])->field('id,name')->find();
            if($cityInfo){
                $customerInfo['areaname']=$cityInfo['name'];
            }else{
                $customerInfo['areaname']='暂无';
            }
            //录入人信息
            $userInfo=Db::name('love_admin_user')->where(['id'=>$customerInfo['inputuserid']])->field('id,name')->find();
            $customerInfo['inputName']=$userInfo['name'];
            //跟进人信息
            $userInfos=Db::name('love_admin_user')->where(['id'=>$customerInfo['floweuserid']])->field('id,user_name,name')->find();
            if($userInfos){
                $customerInfo['genjinrenName']=$userInfos['name'];
                $customerInfo['genjinrenPhone']=$userInfos['user_name'];
            }else{
                $customerInfo['genjinrenName']='暂无';
                $customerInfo['genjinrenPhone']='暂无';
            }

            //获取到访凭证，签约备注，已买备注信息
            $folowInfo=Db::name('love_follow')->where(['customerId'=>$customerId,'userId'=>$customerInfo['floweuserid'],'type'=>['in','2,3,4']])->order('type')->select()->toArray();
            $customerInfo['daofanginfo']=[];
            $customerInfo['qianyueinfo']=[];
            $customerInfo['yimaiinfo']=[];
            if($folowInfo){
                foreach($folowInfo as $k=>$v){
                    //var_dump(json_decode($v['imageIds'],'true'));
                    $folowInfo[$k]['imageInfo']=$this->getImageUrl(json_decode($v['imageIds'],'true'));
                    $folowInfo[$k]['createTime']=date('Y-m-d H:i:s',$v['createTime']);
                    if($v['type']==2){
                        $customerInfo['daofanginfo']=$folowInfo[$k];
                    }elseif ($v['type']==3){
                        $customerInfo['qianyueinfo']=$folowInfo[$k];
                    }else{
                        $customerInfo['yimaiinfo']=$folowInfo[$k];
                    }
                }
            }
            //获取跟进信息
            $fol=Db::name('love_follow')->where(['customerId'=>$customerId,'userId'=>$customerInfo['floweuserid'],'type'=>1])->order('createTime desc')->select()->toArray();
            //跟进人名称
            if($fol){
                foreach($fol as $k=>$v){
                    $fol[$k]['genjinrenname']=Db::name('love_admin_user')->where(['id'=>$v['userid']])->field('id,name')->find()['name'];
                    $fol[$k]['createTime']=date('Y-m-d H:i:s',$v['createTime']);
                }
            }
            $customerInfo['fol']=$fol;
            $customerInfo['createTime']=date('Y-m-d H:i:s',$customerInfo['create_time']);
            if($customerInfo['visit_time']){
                $customerInfo['visit_time']=date('Y-m-d H:i:s',$customerInfo['visit_time']);
            }
            //处理客户标签
            if($customerInfo['flagstr']){
                $customerInfo['flagstrnew']=explode('@',$customerInfo['flagstr']);
            }
            if(($customerInfo['inputuserid']!=$this->userId)&&($customerInfo['floweuserid']!=$this->userId)&&$customerInfo['datatype']!=2&&$customerInfo['datatype']!=3){
                $customerInfo['isshow']=false;
                $customerInfo['phone']=substr($customerInfo['phone'], 0, 3).'****'.substr($customerInfo['phone'],7);
            }else{
                $customerInfo['isshow']=true;
            }
            return json(['msg'=>'获取成功','code'=>'success','data'=>$customerInfo]);
        }
        //编辑
        $editData=$this->postData();
        //性别，状态
        $newedit['status']=$editData['status'];//1:跟进中 2：已付订 3.已签约 4.预失效 5.失效
        $newedit['gender']=$editData['gender'];
        $newedit['flagstr']=$editData['flagstr'];
        if($customerInfo['status']==2 &&$newedit['status']!=3){
            return json(['msg'=>'该客户已付订','code'=>'error','data'=>[]]);
        }
        //卖，出租客户编辑判断
        if($customerInfo['datatype']==2||$customerInfo['datatype']==3){
            if(!empty($customerInfo['floweuserid'])){
                if($customerInfo['floweuserid']!=$this->userId){
                    return json(['msg'=>'该客户已有人跟进','code'=>'error','data'=>[]]);
                }
            }else{
                $editData['floweuserid']=$this->userId;
                $editData['fenpei_time']=time();
            }
        }
        if($newedit['status']==0){
            return json(['msg'=>'请选择客户状态','code'=>'error','data'=>[]]);
        }
        if($editData['status']==2){
            if(empty($editData['dingjin'])){
                return json(['msg'=>'请输入订金金额','code'=>'error','data'=>[]]);
            }
            $insertData['datatype']=2;
            $newedit['dingjin']=$editData['dingjin'];
        }
        if($editData['status']==3){
            if(empty($editData['qianyue'])){
                return json(['msg'=>'请输入签约金额','code'=>'error','data'=>[]]);
            }
            $insertData['datatype']=3;
            $newedit['qianyue']=$editData['qianyue'];
        }
        if($editData['status']==4){
            if(empty($editData['remark'])){
                return json(['msg'=>'请输入失效备注信息','code'=>'error','data'=>[]]);
            }
            $insertData['datatype']=4;
            $newedit['remark']=$editData['remark'];
        }
        unset($editData['token']);
        unset($editData['userid']);
        unset($editData['flag']);
        unset($editData['customerId']);
        //var_dump($editData);
        $update=Db::name('love_customer')->where(['id'=>$customerId])->update($editData);
        if($update){
            if(in_array($editData['status'],[2,3,4])){
                //写入操作日志记录
                //操作类型 1:录入(进入资源池)  2：付订
                // 3：签约 4 预失效 5.确认失效 6.驳回
                // 7.放回资源池重新分配 8.系统分配
                // 9.转出 10. 区域管理员将过期客户手动分配给其他人员
                $insertData['userid']=$this->userId;
                $insertData['customerid']=$customerId;
                $insertData['fromType']=2;
                $insertData['remark']='编辑客户信息';
                $insertData['create_time']=time();
                Db::name('love_log')->insert($insertData);
            }
            return json(['msg'=>'修改成功','code'=>'success','data'=>[]]);
        }
        return json(['msg'=>'您未修改任何信息','code'=>'error','data'=>[]]);
    }
    /**
     * 获取图片链接
     */
    private function getImageUrl($ids){
        $imageInfos=Db::name('upload_file')->where('file_id','in',$ids)->select();
        $arr=[];
        if($imageInfos){
            foreach($imageInfos as $k=>$v){
                $arr[]=$v['file_url'].'/'.$v['file_name'];
            }
        }
        return $arr;
    }
    /**
     * 客户列表
     */
    public function customerList(){
        //销售管理员获取自己录入+楼管分配+所有出租+所有卖+下级置业顾问的客户；置业顾问获取自己录入+楼管分配+所有出租+所有卖
        $userInfo=Db::name('love_admin_user')->where(['id'=>$this->userId])->field('password',true)->find();
        //构建查询条件
        $status=input('post.status');//1:跟进中 2：已付订 3.已签约 4.预失效 5.失效
        $genjinStatus=input('post.genjinStatus');//1 待跟进  2 已跟进
        $namephone=input('post.namephone');//客户姓名或者手机号码
        $paixu=input('post.paixu');
        $dataType=input('post.datatype');//1:买  2：卖 3：出租 4：求租
        $iszl=input('post.iszl');//1自录  2 分配 默认传0
        if($iszl){
            if($iszl==1){
                $where['inputuserid']=['=',$this->userId];
            }else{
                $where['inputuserid']=['<>',$this->userId];
            }
        }
        if($dataType){
            $where['datatype']=['=',$dataType];
        }
        $order=['create_time'=>'desc'];
        if($paixu==2){
            $order=['create_time'=>'asc'];
        }else{
            $order=['create_time'=>'desc'];
        }
        //录入时间段  createTime
        $lutimeStart=input('post.luruTimeStart');
        $lutimeEnd=input('post.luruTimeEnd');
        if($lutimeStart&&$lutimeEnd){
            $where['create_time']=['between',[strtotime($lutimeStart),strtotime($lutimeEnd)+86399]];
        }
        if($lutimeStart&&!$lutimeEnd){
            $where['create_time']=['>=',strtotime($lutimeStart)];
        }
        if(!$lutimeStart&&$lutimeEnd){
            $where['create_time']=['<=',strtotime($lutimeEnd)+86399];
        }
        if($genjinStatus==1){
            //待跟进
            $where['visit_time']=[['=',0],['<',time()],'or'];
        }else{
            //已跟进
            $where['visit_time']=['>',time()];
        }
        if($namephone){
            $where['name|phone']=['like','%'.$namephone.'%'];
        }
        if($status){
            $where['status']=['=',$status];
        }
        if($userInfo['type']==6){
            //楼管人员
            $where['inputuserid']=['=',$this->userId];
        }elseif($userInfo['type']==5){
            //置业顾问
            $where['inputuserid|floweuserid']=['=',$this->userId];
            $whereor['datatype']=['in','2,3'];
            if(isset($where['create_time'])){
                $whereor['create_time']=$where['create_time'];
            }
        }else{
            //销售管理员
            //获取所有下级id
            $sonlist=Db::name('love_admin_user')->where(['areaid'=>$userInfo['areaid'],'type'=>5,'loupanids'=>['in',$userInfo['loupanids']]])->field('id,areaid,type')->select()->toArray();
            $newson=[];
            if($sonlist){
                foreach ($sonlist as $k=>$v){
                    $newson[]=$v['id'];
                }
            }
            $newson[]=$this->userId;
            $where['inputuserid|floweuserid']=['in',$newson];
            $whereor['datatype']=['in','2,3'];
            if(isset($where['create_time'])){
                $whereor['create_time']=$where['create_time'];
            }
        }
        if($userInfo['type']==6){
            $customerInfo=Db::name('love_customer')->where($where)->order($order)->select()->toArray();
        }else{
            $customerInfo=Db::name('love_customer')->where($where)->whereOr($whereor)->order($order)->select()->toArray();
        }
        //根据意向楼盘类型确认过期时间
        if($customerInfo){
            foreach ($customerInfo as $k=>$v){
                if(($v['inputuserid']!=$v['floweuserid']) && ($v['datatype']==1||$v['datatype']==4)){
                    $bahuiqi=Db::name('love_expire')->where(['id'=>$v['flagid']])->value('expiretime');//总的过期天数
                    if($v['fenpei_time']==0){
                        $customerInfo[$k]['expire_time']="未分配";
                    }else{
                        $bahuiqitimes=$bahuiqi*86400;
                        $yiguotime=time()-$v['fenpei_time'];
                        if($yiguotime-$bahuiqitimes>0){
                            $customerInfo[$k]['expire_time']='已过期';
                        }else{
                            $customerInfo[$k]['expire_time']=$this->timediff($bahuiqitimes,$yiguotime);
                        }
                    }
                }else{
                    $customerInfo[$k]['expire_time']='';
                }
                //1：主管理员 2：城市管理员 3：区域管理员 4:销售管理员  5：置业顾问 6：楼管人员
                if($userInfo['type']==4){
                    //销售管理员
                    if($v['datatype']==2||$v['datatype']==3){
                        $customerInfo[$k]['isshow']=true;
                    }else{
                        if($v['inputuserid']==$this->userId){
                            $customerInfo[$k]['isshow']=true;
                        }else{
                            if(($v['inputuserid']!=$this->userId)&&($v['floweuserid']!=$this->userId)){
                                $customerInfo[$k]['isshow']=false;
                                $customerInfo[$k]['phone']=substr($v['phone'], 0, 3).'****'.substr($v['phone'],7);
                            }
                        }
                    }
                }
                if($userInfo['type']==5){
                    //置业顾问
                    $customerInfo[$k]['isshow']=true;
                }
                if($userInfo['type']==6){
                    //楼管人员
                    $customerInfo[$k]['isshow']=true;
                }
                $customerInfo[$k]['create_time']=date('Y-m-d H:i:s',$v['create_time']);
                $customerInfo[$k]['inputuser']=Db::name('love_admin_user')->where(['id'=>$v['floweuserid']])->value('name');
            }
        }
        //判断当前登录人买，求租客户待跟进数量是否大于三个(系统分配)
        $daigenjin['visit_time']=[['=',0],['<',time()],'or'];
        $daigenjin['status']=['in','1,4'];
        $daigenjin['floweuserid']=['=',$this->userId];
        $daigenjin['inputuserid']=['<>',$this->userId];
        $counts=Db::name('love_customer')->where($daigenjin)->count();
        if($counts>=3){
            $show=true;
        }else{
            $show=false;
        }
        return json(['msg'=>'获取成功','code'=>'success','data'=>$customerInfo,'isshow'=>$show]);
    }
    /**
     * 获取通知详情
     */
    public function getNotice(){
        $id=input('post.id');
        if(empty($id)){
            return json(['msg'=>'通知id不能为空','code'=>'error','data'=>[]]);
        }
        $info=Db::name('love_notice')->where(['id'=>$id])->find();
        $info['create_time']=date('Y-m-d H:i:s',$info['create_time']);
        return json(['msg'=>'获取成功','code'=>'success','data'=>$info]);
    }
    /**
     * 编辑凭证 跟进信息
     */
    public function editjoininfo(){
        $data=$this->postData();
        if(empty($data['id'])){
            return json(['msg'=>'凭证数据id不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($data['flag'])){
            return json(['msg'=>'操作类型参数不能为空','code'=>'error','data'=>[]]);
        }
        if($data['flag']!='info'&&$data['flag']!='edit'){
            return json(['msg'=>'操作类型参数不正确','code'=>'error','data'=>[]]);
        }
        if($data['flag']=='info'){
            //获取详情数据
            $followInfo=Db::name('love_follow')->where(['id'=>$data['id']])->find();
            if($followInfo['type']!=1){
                $followInfo['imageInfo']=  $this->getImageUrl(json_decode($followInfo['imageIds'],'true'));
            }else{
                $followInfo['imageInfo']=[];
                $followInfo['createTime']=date('Y-m-d H:i:s',$followInfo['createTime']);
                if($followInfo['visitTime']){
                    $followInfo['visitTime']=date('Y-m-d H:i:s',$followInfo['visitTime']);
                }else{
                    $followInfo['visitTime']=0;
                }
            }
            $followInfo['imageIds']=json_decode($followInfo['imageIds'],true);
            return json(['msg'=>'获取成功','code'=>'success','data'=>$followInfo]);
        }else{
            //修改提交数据
            $followInfos=Db::name('love_follow')->where(['id'=>$data['id']])->find();
            //只有驻场人员可以修改凭证信息
            if(empty($data['content'])){
                return json(['msg'=>'内容不能为空','code'=>'error','data'=>[]]);
            }
            if($followInfos['type']!=1){
                if(empty($data['imageIds'])){
                    return json(['msg'=>'图片id参数不能为空','code'=>'error','data'=>[]]);
                }
            }
        }
        //$data['imageIds']=$data['imageIds'];
        $data['updateTime']=time();
        $cus['visitTime']=strtotime($data['visitTime']);
        unset($data['flag']);
        unset($data['token']);
        $data['visitTime']=strtotime($data['visitTime']);
        $insert=Db::name('love_follow')->where(['id'=>$data['id']])->update($data);
        if($insert){
            return json(['msg'=>'更新成功','code'=>'success','data'=>[]]);
        }
        return json(['msg'=>'更新失败','code'=>'error','data'=>[]]);
    }
    /**
     * 将分配的客户转出
     */
    public function export(){
        $flag=input('post.flag');//操作参数  info  add
        $customerId=input('post.customerid');//客户id
        if(empty($flag)){
            return json(['msg'=>'操作参数不能为空','code'=>'error','data'=>[]]);
        }
        if($flag!='info'&&$flag!='add'){
            return json(['msg'=>'操作参数不正确','code'=>'error','data'=>[]]);
        }
        if($flag=='info'){
            //获取客户基本信息
            $customerInfo=Db::name('love_customer')->where(['id'=>$customerId])->field('id,datatype,flagid,cityid,areaid')->find();
            //获取城市，区域联动信息
            /*$roleList=Db::name('love_area')->where(['pid'=>0,'status'=>1])->field('id,name,pid')->select()->toArray();
            //获取城市,区域,楼盘三级联动
            foreach ($roleList as $k=>$v){
                $city=Db::name('love_area')->where(['pid'=>$v['id'],'status'=>1])->field('id,name,pid')->select()->toArray();
                $roleList[$k]['city']=$city;
            }*/
            $roleList=Db::name('love_area')->where(['pid'=>0])->field('id,name,pid')->select()->toArray();
            //获取城市,区域,楼盘三级联动
            foreach ($roleList as $k=>$v){
                $city=Db::name('love_area')->where(['pid'=>$v['id'],'status'=>1])->field('id,name,pid')->select()->toArray();
                $roleList[$k]['city']=$city;
                foreach ($roleList[$k]['city'] as $k1=>$v1){
                    $region=Db::name('love_building')->where(['areaId'=>$v1['id']])->field('id,name')->select()->toArray();
                    $roleList[$k]['city'][$k1]['region']=$region;
                }
            }
            $new=[];
            foreach ($roleList as $k=>$v){
                if(empty($v['city'])){
                    unset($roleList[$k]);
                }else{
                    $new[]=$v;
                }
            }
            //获取客户类型  客户类型 1:买  2：卖 3：出租 4：求租
            $list=['买','卖','出租','求租'];
            $data['customerinfo']=$customerInfo;
            $data['araeinfo']=$new;
            $data['datainfo']=$list;
            return json(['msg'=>'获取成功','code'=>'success','data'=>$data]);
        }
        //编辑信息
        $cityid=input('post.cityid');
        $areaid=input('post.areaid');
        $datatype=input('post.datatype');
        $remark=input('post.remark');
        $loupanid=input('post.loupanid');
        if(empty($loupanid)){
            return json(['msg'=>'请选择楼盘','code'=>'error','data'=>[]]);
        }
        if(empty($cityid)){
            return json(['msg'=>'请选择城市信息','code'=>'error','data'=>[]]);
        }
        if(empty($areaid)){
            return json(['msg'=>'请选择区域信息','code'=>'error','data'=>[]]);
        }
        if(empty($datatype)){
            return json(['msg'=>'请选择客户类型','code'=>'error','data'=>[]]);
        }
        if(empty($remark)){
            return json(['msg'=>'请输入备注信息','code'=>'error','data'=>[]]);
        }
        //更新客户信息，将客户放入资源池
        $update=Db::name('love_customer')->where(['id'=>$customerId])->update(['datatype'=>$datatype,'loupanid'=>$loupanid
            ,'cityid'=>$cityid,'areaid'=>$areaid,'fenpei_time'=>0,'status'=>1,'update_time'=>time(),'floweuserid'=>0,'visit_time'=>0]);
        //写入日志记录
        $insert['userid']=$this->userId;
        $insert['datatype']=9;
        $insert['fenpeiid']=0;
        $insert['customerid']=$customerId;
        $insert['fromType']=2;
        $insert['remark']=$remark;
        $insert['create_time']=time();
        $i=Db::name('love_log')->insertGetId($insert);
        if($i){
            return json(['msg'=>'转出成功','code'=>'success','data'=>[]]);
        }
        return json(['msg'=>'转出失败','code'=>'error','data'=>[]]);
    }
    /**
     * 获取保护期时间
     */
    private function timediff($begin_time,$end_time){
        if($begin_time < $end_time){
            $starttime = $begin_time;
            $endtime = $end_time;
        }else{
            $starttime = $end_time;
            $endtime = $begin_time;
        }
        //计算天数
        $timediff = $endtime-$starttime;
        $days = intval($timediff/86400);
        //计算小时数
        $remain = $timediff%86400;
        $hours = intval($remain/3600);
        //计算分钟数
        $remain = $remain%3600;
        $mins = intval($remain/60);
        //计算秒数
        $secs = $remain%60;
        //$res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
        $res = $days.'天'.$hours.'小时'.$mins.'分';
        return $res;
    }
    /**
     * 上传图片
     */
    public function upload(){
        $fileKey = request()->file('file');
        $userInfo=Db::name('love_admin_user')->where(['id'=>$this->userId])->find();
        $res=Image::open($fileKey);
        $KeyId = $this->config['engine'][$this->config['default']]['access_key_id'];
        $KeySecret =$this->config['engine'][$this->config['default']]['access_key_secret'];
        $EndPoint = $this->config['engine'][$this->config['default']]['domain'];
        $Bucket = $this->config['engine'][$this->config['default']]['bucket'];
        $ossClient = new OssClient($KeyId, $KeySecret, $EndPoint);
        $fname='小程序端/';
        $fileName = $fname. sha1(date('YmdHis', time()) . uniqid()) . '.' . $res->type();
        //执行阿里云上传
        $result = $ossClient->uploadFile($Bucket, $fileName, $fileKey->getInfo()['tmp_name']);
        $fileType =$fileKey->getInfo()['type'];
        // 信息
        $fileInfo = $fileKey->getInfo();
        $uploadFile = $this->addUploadFile(-1, $fileName, $fileInfo, $fileKey->getInfo()['name'],$fileType,$userInfo);
        // 图片上传成功
        return json(['code' => 1, 'msg' => '上传成功', 'data' => $uploadFile]);
    }
    /**
     * 添加文件库上传记录
     */
    private function addUploadFile($group_id, $fileName, $fileInfo, $old_name,$fileType,$user){
        // 存储引擎
        $storage = $this->config['default'];
        // 存储域名
        $fileUrl = isset($this->config['engine'][$storage]['domain'])?$this->config['engine'][$storage]['domain'] : '';
        // 添加文件库记录
        $model = new UploadFile;
        //记录上传图片的公司id
        $model->add([
            'group_id' => $group_id > 0 ? (int)$group_id : 0,
            'storage' => $storage,
            'file_url' => 'https://img.aishenghuolife.cn',
            'file_name' => $fileName,
            'is_user'=>1,
            'file_size' => $fileInfo['size'],
            'file_type' => $fileType,
            'old_name' => $old_name,
            'userid'=> $user['id'],
            'extension' => pathinfo($fileInfo['name'], PATHINFO_EXTENSION),
        ]);
        return $model;
    }
    /**
     * 添加凭证 签约  预定  跟进信息
     */
    public function addInfo(){
        $data=$this->postData();
        if(empty($data['userid'])){
            return json(['msg'=>'当前登录人id不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($data['content'])){
            return json(['msg'=>'内容不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($data['customerId'])){
            return json(['msg'=>'客户id不能为空','code'=>'error','data'=>[]]);
        }
        if(empty($data['type'])){
            return json(['msg'=>'操作类型不能为空','code'=>'error','data'=>[]]);
        }
        $users=Db::name('love_admin_user')->where(['id'=>$data['userid']])->value('type');//1:跟进信息 2：到访凭证  3：签约备注  4 ：已买备注
        if($data['type']!=1){
            if(empty($data['imageIds'])){
                return json(['msg'=>'图片id参数不能为空','code'=>'error','data'=>[]]);
            }
        }
        //判断当前客户状态
        $customerInfo=Db::name('love_customer')->where(['id'=>$data['customerId']])->find();
        //1:跟进中 2：已付订 3.已签约 4.预失效 5.失效
        if($customerInfo&&$customerInfo['status']==5){
            return json(['msg'=>'当前客户已失效','code'=>'error','data'=>[]]);
        }
        if($customerInfo&&$customerInfo['status']==4){
            return json(['msg'=>'当前客户已设置预失效，待后台审核','code'=>'error','data'=>[]]);
        }
        //$data['imageIds']=json_encode($data['imageIds']);
        $data['createTime']=time();
        $data['updateTime']=0;

        if(empty($data['visitTime'])&&$data['type']==1){
            return json(['msg'=>'请选择下次约访时间','code'=>'error','data'=>[]]);
        }else{
            $cus['visitTime']=strtotime($data['visitTime']);
        }
        unset($data['token']);
        if($cus['visitTime']){
            //下次约访时间据当前时间间隔1天
            if($cus['visitTime']<strtotime(date('Y-m-d',strtotime('+1 day')))){
                return json(['msg'=>'下次约访时间距离当前时间至少一天','code'=>'error','data'=>[]]);
            }
            //更新下次约访时间
            Db::name('love_customer')->where(['id'=>$data['customerId']])->update(['visit_time'=>$cus['visitTime']]);
        }
        $data['visitTime']=strtotime($data['visitTime']);
        $insert=Db::name('love_follow')->insertGetId($data);
        if($insert){
            return json(['msg'=>'添加成功','code'=>'success','data'=>[]]);
        }
        return json(['msg'=>'添加失败','code'=>'error','data'=>[]]);
    }
    /**
     * 个人中心
     */
    public function center(){
        $userInfo=Db::name('love_admin_user')->where(['id'=>$this->userId])->field('password',true)->find();
        $imageInfo=Db::name('upload_file')->where(['file_id'=>$userInfo['imageid']])->find();
        if($imageInfo){
            $userInfo['imageurl']=$imageInfo['file_url'].'/'.$imageInfo['file_name'];
        }else{
            $userInfo['imageurl']='';
        }
        return json(['msg'=>'获取成功','code'=>'success','data'=>$userInfo]);
    }
    /**
     * 修改个人头像
     */
    public function editImage(){
        $imageId=input('post.imageid');
        $update=Db::name('love_admin_user')->where(['id'=>$this->userId])->update(['imageid'=>$imageId]);
        if($update){
            return json(['msg'=>'修改成功','code'=>'success','data'=>[]]);
        }
        return json(['msg'=>'修改失败','code'=>'error','data'=>[]]);
    }
    /**
     * 修改密码
     */
    public function updatePass(){
        $phone=input('post.phone');
        $code=input('post.code');
        $password=input('post.password');
        $repassword=input('post.repassword');
        if (empty($phone)){
            return json(['msg'=>'手机号不能为空','code'=>'error','data'=>[]]);
        }
        if (empty($code)){
            return json(['msg'=>'验证码不能为空','code'=>'error','data'=>[]]);
        }
        if (empty($password)){
            return json(['msg'=>'新密码不能为空','code'=>'error','data'=>[]]);
        }
        if (empty($repassword)){
            return json(['msg'=>'确认密码不能为空','code'=>'error','data'=>[]]);
        }
        //手机号正则验证
        $chars = "/^1[345789]\d{9}$/";
        if(!preg_match($chars,$phone)){
            return json(['msg'=>'手机号格式不正确','code'=>'error','data'=>[]]);
        }
        $ccode=Cache::get($phone);
        if($ccode){
            if($code!=$ccode){
                return json(['msg'=>'验证码不正确','code'=>'error','data'=>[]]);
            }
        }else{
            return json(['msg'=>'验证码已过期','code'=>'error','data'=>[]]);
        }
        if($password!=$repassword){
            return json(['msg'=>'两次输入密码不一致','code'=>'error','data'=>[]]);
        }
        $update=Db::name('love_admin_user')->where(['user_name'=>$phone])->update(['password'=>md5($password),'update_time'=>time()]);
        if($update){
            Cache::rm($phone);
            return json(['msg'=>'密码修改成功','code'=>'success','data'=>[]]);
        }
        return json(['msg'=>'密码修改失败','code'=>'error','data'=>[]]);
    }

    /**
     * 发送验证码
     */
    public function sendMessage(){
        $phone=input('post.phone');
        if (empty($phone)){
            return json(['msg'=>'手机号不能为空','code'=>'error','data'=>[]]);
        }
        //手机号正则验证
        $chars = "/^1[345789]\d{9}$/";
        if(!preg_match($chars,$phone)){
            return json(['msg'=>'手机号格式不正确','code'=>'error','data'=>[]]);
        }
        $info=Db::name('love_admin_user')->where(['user_name'=>$phone])->find();
        if(empty($info)){
            return json(['msg'=>'该账户不存在','code'=>'error','data'=>[]]);
        }
        $code=rand(pow(10,(6-1)), pow(10,6)-1);
        Cache::set($phone,$code,120);
        $res=$this->sendcode($phone,$code);
        if($res['Message']=='OK'){
            return json(['msg'=>'发送成功','code'=>'success','data'=>$code]);
        }
        Cache::rm($phone);
        return json(['msg'=>'发送失败,'.$res['Message'],'code'=>'error','data'=>[]]);
    }

    public function sendcode($phone,$code){
        $path = __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'vendor' . \DIRECTORY_SEPARATOR . 'autoload.php';
        if (file_exists($path)) {
            require_once $path;
        }
        return Sms::main($phone,$code);
    }
    /**
     * 买  求租 获取意向 城市  区域  楼盘
     */
    public function getArea(){
        $type=input('post.types');
        $roleList=Db::name('love_area')->where(['pid'=>0])->field('id,name,pid')->select()->toArray();
        //获取城市,区域,楼盘三级联动
        foreach ($roleList as $k=>$v){
            $city=Db::name('love_area')->where(['pid'=>$v['id'],'datatype'=>$type,'status'=>1])->field('id,name,pid')->select()->toArray();
            $roleList[$k]['city']=$city;
            foreach ($roleList[$k]['city'] as $k1=>$v1){
                $region=Db::name('love_building')->where(['areaId'=>$v1['id']])->field('id,name')->select()->toArray();
                $roleList[$k]['city'][$k1]['region']=$region;
            }
        }
        $new=[];
        foreach ($roleList as $k=>$v){
            if(empty($v['city'])){
                unset($roleList[$k]);
            }else{
                $new[]=$v;
            }
        }
        return json(['code' => 'success', 'msg' => '获取成功', 'data' => $new]);
    }
    /**
     * 退出登录
     */
    public function loginOut(){
        if(Cache::rm($this->userId.'token')){
            return json(['msg'=>'退出成功','code'=>'success','data'=>[]]);
        }
        return json(['msg'=>'退出失败','code'=>'error','data'=>[]]);
    }
    /**
     * 添加客户获取意向类型
     */
    public function getcusType(){
        $info=Db::name('love_expire')->where(['is_delete'=>0])->select()->toArray();
        return json(['msg'=>'获取成功','code'=>'success','data'=>$info]);
    }
    /**
     * 测试sql
     */
    public function testSql(){
        $info=Db::name('love_customer')->order('create_time desc')->limit(1)->find();
        return json(['msg'=>'获取成功','code'=>'success','data'=>$info]);
    }
    /**
     * 获取某个区域下的所有销售人员
     */
    public function getxiaoshou(){
        $userInfo=Db::name('love_admin_user')->where(['areaid'=>4,'type'=>['in','4,5'],'is_delete'=>0])
            ->field('id')->select()->toArray();
        $logInfo=Db::name('love_distribution_log')->where(['areaid'=>4])->order('create_time desc')->limit(1)->find();
        $length=count($userInfo);
        if($logInfo){
            foreach ($userInfo as $k1=>$v1){
                if($v1['id']==$logInfo['userid'] && $k1!=$length-1){
                    $id=$userInfo[$k1+1]['id'];
                }elseif($v1['id']==$logInfo['userid'] && $k1==$length-1){
                    $id=$userInfo[0]['id'];
                }
            }
        }else{
            $id=$userInfo[0]['id'];
        }
        return json(['msg'=>'获取成功','code'=>'success','用户信息'=>$userInfo,'shangci'=>$logInfo['userid'],'data'=>$id]);
    }
    /**
     * 生成小程序二维码
     */
    public function qrcode(){
        //商品详情
        $user_id=input('post.buildid');
        $show=input('post.fenxiangId');
        if(empty($user_id)){
            return json(['msg'=>'buildid不能为空','code'=>'error','data'=>[]]);
        }
        $GiftsModel=new GiftsModel();
        $detail = $GiftsModel->getImage($user_id,$show);
        return json(['msg'=>'获取二维码链接成功','code'=>'success','data'=>$detail]);
    }

    /**
     * 测试接口
     */
    public function test(){
        //获取买、求租/跟进人id为空客户/楼管录入/的客户信息
        /*$toBeAssignedInfos=Db::name('love_customer')->where(['datatype'=>['in','1,4'],'floweuserid'=>['<',1],'iszilu'=>2])
            ->field('id,datatype,floweuserid,iszilu,cityid,areaid')->select()->toArray();
        if(empty($toBeAssignedInfos)){
            Log::mylog('未获取到客户日志(log)：','未获取到客户信息','test-nocustomer');
            return json(['msg'=>'未获取到客户信息','code'=>'error','data'=>[]]);
        }*/
        $toBeAssignedInfos=[["id"=>5,"datatype"=>1,"floweuserid"=>0,"iszilu">2,"cityid"=>1,"areaid"=>3]];
        //分配客户
        foreach($toBeAssignedInfos as $k=>$v){
            //根据待分配客户的意向区域获取对应销售组织账号
            /*$userInfo=Db::name('love_admin_user')->where(['areaid'=>$v['areaid'],'type'=>['in','4,5'],'is_delete'=>0])
                ->field('id')->select()->toArray();*/
            $userInfo=[["id"=>7]];

            if(!$userInfo){
                Log::mylog('未获取到销售人员(log)：','未获取到销售人员','test-nouser');
                continue;
            }else{
                //构建待分配数据池 //锁定本次被分配人id
                $id=0;
                $length=count($userInfo);
                $newarray=[];
                foreach ($userInfo as $k11=>$v11){
                    $newarray[]=$v11['id'];
                }
                $flag=0;
                foreach ($userInfo as $k1=>$v1){
                    //查询上一次对应组织被分配人id
                    $logInfo=Db::name('love_distribution_log')->where(['areaid'=>$v['areaid']])->order('id desc')->limit(1)->find();
                    if($logInfo){
                        $keys=array_search($logInfo['userid'], $newarray);
                        if($keys==$length-1){
                            $id=$userInfo[0]['id'];
                        }else{
                            $id=$userInfo[$keys+1]['id'];
                        }
                    }else{
                        $id=$userInfo[0]['id'];
                    }
                    if(!$flag){
                        $flag=$id;
                    }
                    Log::mylog('测试日志：','被分配的销售id:'.$id,'test-fenpeiCustomer');
                    $where['visit_time']=[['=',0],['<',time()],'or'];
                    $where['inputuserid']=['<>',$id];
                    $where['floweuserid']=['=',$id];
                    $where['status']=['=',1];
                    $count=Db::name('love_customer')->where($where)->count();
                    if($id==7){
                        $count=3;
                    }
                    if($count>=3){
                        Log::mylog('测试日志：','不符合的id:'.$id,'test-bufuhe');
                        $data['areaid']=$v['areaid'];
                        $data['userid']=$id;
                        $data['customerid']=$v['id'];
                        $data['create_time']=time();
                        $data['status']=2;
                        Db::name('love_distribution_log')->insert($data);
                        $xx=0;
                        foreach ($newarray as $kk=>$vv){
                            if($newarray[0]==$flag){
                                $xx=$newarray[count($newarray)-1];
                            }else{
                                if($flag==$vv){
                                    $xx=$newarray[$kk-1];
                                }
                            }
                        }
                        if($id==$xx){
                            Log::mylog('测试日志：','一轮结束id:'.$id,'test-zd');
                            break;
                        }else{
                            Log::mylog('测试日志：','不符合，进行下一条数据判断，不符合id:'.$id,'test-next');
                            continue;
                        }
                    }else{
                        //如果一轮结束跳出循环
                        //如果符合完成分配 //修改客户表，写入分配日志、流程日志 跳出分配
                        Log::mylog('测试日志：','被更新的销售id:'.$id,'notify-updateCustomer');
                        //$updateCustomer=Db::name('love_customer')->where(['id'=>$v['id']])->update(['floweuserid'=>$id,'fenpei_time'=>time()]);
                        $data['areaid']=$v['areaid'];
                        $data['userid']=$id;
                        $data['customerid']=$v['id'];
                        $data['create_time']=time();
                        $data['status']=1;
                        Db::name('love_distribution_log')->insert($data);
                        //写入操作日志
                        $logdata['userid']=0;
                        $logdata['datatype']=8;
                        $logdata['fenpeiid']=$id;
                        $logdata['customerid']=$v['id'];
                        $logdata['fromType']=2;
                        $logdata['remark']='系统分配';
                        $logdata['create_time']=time();
                        Db::name('love_log')->insert($logdata);
                        break;
                    }
                }
            }
        }
    }

    //更新客户是否允许发送消息通知
    public function isyx(){
        $status=input('post.status');
        $s=Db::name('love_admin_user')->where(['id'=>$this->userId])->update(['isyx'=>$status]);
        return json(['msg'=>'操作成功','code'=>'success','data'=>[]]);
    }

    //订阅消息发布
    public function sendMessages(){
        $appid = 'wx0580bdcba326b43d';
        $appsecret = 'cf1dac072e4d51a5d5308d4cc91b487b';
        $touser = input('post.openid');
        $template_id = 'SYbMtiQnN3xwhx5LYoVssnn3HsM8Q3-kh6L-EF8dI8U';
        $page = '';
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
        $res = json_decode(file_get_contents($url),true);
        $access_token = $res['access_token'] ;
        //请求url
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token ;
        //发送内容
        $data = [] ;
        //接收者（用户）的 openid
        $data['touser'] = $touser;
        //所需下发的订阅模板id
        $data['template_id'] = $template_id ;
        //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
        $data['page'] = '/pages/shouye/shouye' ;
        //模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
        $data['data'] = [
            "thing1"=>[
                'value' => '张三'
            ],
            "thing2"=>[
                'value' => '海伦春天'
            ],
            "time4"=>[
                'value' => date("Y-m-d H:i:s")
            ],
            'phrase7'=>[
                'value'=>'待跟进'
            ],
        ];
        //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        $data['miniprogram_state'] = 'developer' ;
        return self::curlPost($url,json_encode($data)) ;
    }
//发送post请求
    static function curlPost($url,$data)
    {
        $ch = curl_init();
        $params[CURLOPT_URL] = $url;    //请求url地址
        $params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        $params[CURLOPT_POST] = true;
        $params[CURLOPT_POSTFIELDS] = $data;
        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接
        return $content;
    }

}
